from django.shortcuts import render,get_object_or_404
from django.http import HttpResponse,HttpResponseRedirect
from django.template import loader
from .models import Question,Choice
from django.http import Http404
from django.urls import reverse
# Create your views here.

def index(request):#问卷“index”页：显示最新的一些问卷
    latest_question_list = Question.objects.order_by('-pub_date')[:5]#减号是倒序的意思
    template = loader.get_template('polls/index.html')#上面的代码会加载polls/index.html文件，并传递给它一个参数。这个参数是一个字典，包含了模板变量名和Python对象之间的映射关系。
    context = {
        'latest_question_list': latest_question_list,
    }
    pass
    return HttpResponse(template.render(context, request))

#def index(request):#问卷“index”页：显示最新的一些问卷
#    latest_question_list = Question.objects.order_by('-pub_date')[:5]
#    context = {'latest_question_list': latest_question_list}
#    return render(request, 'polls/index.html', context)#render是HttpResponse的简写  render函数返回一个经过字典数据渲染过的模板封装而成的HttpResponse对象。

#def detail(request, question_id):#问卷“detail”页面：显示一个问卷的详细文本内容，没有调查结果但是有一个投票或调查表单。
#    try:
#        question = Question.objects.get(pk=question_id)
#    except Question.DoesNotExist:
#        raise Http404("Question does not exist")
#    return render(request, 'polls/detail.html', {'question': question})

def detail(request, question_id):#问卷“detail”页面：显示一个问卷的详细文本内容，没有调查结果但是有一个投票或调查表单。
    question = get_object_or_404(Question, pk=question_id)#替代上面的多行代码，那就是get_object_or_404()方法
    #还有一个get_list_or_404()方法，和上面的get_object_or_404()类似，只不过是用来替代filter()函数，当查询列表为空时弹出404错误。
    return render(request, 'polls/detail.html', {'question': question})
    #在模板系统中圆点.是万能的魔法师，你可以用它访问对象的属性。在例子{{ question.question_text }}中，DJango首先会在question对象中尝试查找一个字典，如果失败，则尝试查找属性，如果再失败，则尝试作为列表的索引进行查询。

#def results(request, question_id):#问卷“results”页面：显示某个问卷的投票或调查结果。
#    response = "You're looking at the results of question %s."
#    return HttpResponse(response % question_id)

def results(request, question_id):
    question = get_object_or_404(Question, pk=question_id)
    return render(request, 'polls/results.html', {'question': question})

#def vote(request, question_id):
#    return HttpResponse("You're voting on question %s." % question_id)

def vote(request, question_id):
    question = get_object_or_404(Question, pk=question_id)
    try:
        selected_choice = question.choice_set.get(pk=request.POST['choice'])
    except (KeyError, Choice.DoesNotExist):
        return render(request, 'polls/detail.html', {
            'question': question,
            'error_message': "You didn't select a choice.",
        })
    else:
        selected_choice.votes += 1
        selected_choice.save()
        return HttpResponseRedirect(reverse('polls:results', args=(question.id,)))
